#!/usr/bin/env python
# coding: utf-8

import json
import logging
import os
import pyodbc
import re
import sys
import traceback

reload(sys)
sys.setdefaultencoding('utf-8')


def cur_file_dir():
    # 获取脚本路径
    path = sys.path[0]
    # 判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)


temp_pwd = cur_file_dir() + '/temp/'

dirs = os.listdir(temp_pwd)


# 创建顾客
def createCustomer(uin, wxh, nickName):
    conn = pyodbc.connect(r'DSN=MYMSSQL;DATABASE=CD20151104105802;UID=bqf2016;PWD=admin888')
    cursor = conn.cursor()
    try:
        sql = "SELECT t_login.FItemID as userid, t_Team.FDeptID as depid, t_VXManage.FItemID as wxid FROM wx_relation, t_VXManage, t_login, t_TeamEntry, t_Team WHERE wx_relation.wxid = t_VXManage.FItemID AND t_VXManage.FUserID = t_login.FItemID AND t_TeamEntry.FEmpID = t_login.FItemID AND t_Team.FItemID = t_TeamEntry.FItemID AND wx_relation.uin = '" + uin + "'"
        cursor.execute(sql)
        row = cursor.fetchone()
    except:
        traceback.print_exc()
    try:
        sql = "INSERT INTO t_Customer (FVXQQ,FItemClassID,FSourceID,FDeptID,FLevel,FEmpID,FNumber,FName,FConVX,FSG,FTZ,FTX,FValues,FJFDate,FAddUserID,FAddDate,FDeleted,FChecked,FSH_WL,FSex,FSF)VALUES "
        sql = sql + "(?,?,?,?,?,?,NEWID(),?,?,?,?,?,?,GETDATE(),?,GETDATE(),?,?,?,?,?)"
        cursor.execute(sql, wxh, 0, 3, str(row[1]), 115, str(row[0]), nickName, str(row[2]), 75, 76, 77, 14,
                       str(row[0]), 0, 0, 13, u'男', u'山东')
        conn.commit()
    except:
        traceback.print_exc()
    cursor.close()
    conn.close()


conn = pyodbc.connect(r'DSN=MYMSSQL;DATABASE=CD20151104105802;UID=bqf2016;PWD=admin888')
cursor = conn.cursor()

for k in dirs:
    counts = 0
    if k.startswith(".") == False:
        subFiles = os.listdir(temp_pwd + '/' + k)
        for k1 in subFiles:
            if k1.startswith("data"):
                try:
                    file_object = open('temp/' + k + '/' + k1, "r")
                    arr = file_object.readlines()

                    for k2 in arr:
                        k2 = k2.replace("\n", "")
                        if k2 != "":
                            date = k2[0:19]
                            content = k2[24:]
                            cJson = json.loads(content)
                            sql = " insert into wx_add (wxh,add_date,content,nick_name) values (?,?,?,?)"
                            nickName = cJson['NickName']
                            wxh = cJson['Alias']
                            if nickName != '':
                                dr = re.compile(r'<[^>]+>', re.S)
                                dd = dr.sub('', nickName)
                                nickName = dd
                                nickName = nickName.replace(" ", "")
                                if len(nickName) >= 50:
                                    nickName = nickName[0:25]
                                # 创建添加记录
                                cursor.execute(sql, k, date, content, nickName)
                                sql = "SELECT b.uin FROM wx_status a, wx_relation b, t_Submessage c WHERE a.wxh = c.FName AND b.wxid = c.FItemID AND c.FParentID = 19 AND wxh = ?";
                                cursor.execute(sql, k)
                                row = cursor.fetchone()
                                uin = row[0]
                                # 创建客户档案
                                sql = "SELECT t_login.FItemID as userid, t_Team.FDeptID as depid, t_VXManage.FItemID as wxid FROM wx_relation, t_VXManage, t_login, t_TeamEntry, t_Team WHERE wx_relation.wxid = t_VXManage.FItemID AND t_VXManage.FUserID = t_login.FItemID AND t_TeamEntry.FEmpID = t_login.FItemID AND t_Team.FItemID = t_TeamEntry.FItemID AND wx_relation.uin = ? "
                                cursor.execute(sql, uin)
                                row = cursor.fetchone()
                                sql = "INSERT INTO t_Customer (FVXQQ,FItemClassID,FSourceID,FDeptID,FLevel,FEmpID,FNumber,FName,FConVX,FSG,FTZ,FTX,FValues,FJFDate,FAddUserID,FAddDate,FDeleted,FChecked,FSH_WL,FSex,FSF)VALUES "
                                sql = sql + "(?,?,?,?,?,?,NEWID(),?,?,?,?,?,?,?,?,GETDATE(),?,?,?,?,?)"
                                cursor.execute(sql, wxh, 0, 3, str(row[1]), 115, str(row[0]), nickName, str(row[2]), 75,
                                               76, 77, 14, date, str(row[0]), 0, 0, 13, u'男', u'山东')
                                counts = counts + 1

                    file_object.close()
                    # 提交成功后删除文件
                    # os.remove('temp/' + k + '/' + k1)
                except Exception, e:
                    logging.error(k + " " + k1 + " " + k2 + " " + str(e));
                    traceback.print_exc()
        # 统计下该时间段内该号的加粉数量，更新到最近的一个使用该号的推广子订单里去
        sql = "SELECT TOP 1 a.FID FROM TG_OrderEntry a, TG_Order b, t_Submessage c WHERE a.FInterID = b.FInterID AND b.FCheck1 = 1 AND a.FJFQty IS NULL AND c.FParentID = 19 AND a.FWXID = c.FItemID AND c.FName = ? ORDER BY b.FEndDate DESC, b.FBillNo DESC ";
        cursor.execute(sql, k)
        row = cursor.fetchone()
        fid = row[0]
        sql = " update TG_OrderEntry set FJFQty = ? where FID = ? "
        cursor.execute(sql, counts, fid)
        conn.commit()
cursor.close()
conn.close()
